/*
 * File: exercise10.cpp
 * -------------------
 * replaceAll
 * compile command :
 * g++ -Wall -g exercise10.cpp -o exercise10 -lStanfordCPPLib -I ../include/
 */

#include <iostream>
#include <string>
using namespace std;

string replaceAll(string str, char c1, char c2);
string replaceAll(string str, string s1, string s2);

int main(void)
{
	cout << replaceAll("nannies", 'n','d') <<endl;
	cout << replaceAll("This is his story", "his","ese") <<endl;
	return 0;
}

string replaceAll(string str, string s1, string s2)
{
	string::size_type position = 0;
	string::size_type newposition = 0;
	string result = "";
	while((newposition=str.find(s1,position))!=string::npos)  
	{  
		result += str.substr(position, newposition-position);
		result += s2;
		position = newposition + s1.length();
	}  
	if(newposition == 0)
		result = str;
	else
		result += str.substr(position);
	return result;
}
string replaceAll(string str, char c1, char c2)
{
	int len = str.length();
	string result= "";
	for(int i = 0; i < len; i++)
	{
		if(str[i] == c1)
			result += c2;
		else
			result += str[i];
	}
	return result;
}
